<template>
  <div id="userTable">
    <el-card class="box-card">
      <div class="text item">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item>
            <el-input v-model.trim="formInline.queryDatas" @keydown.native="keydown($event)" placeholder="小明"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 用户信息表 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column label="Id">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column label="是否启用">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.isActived }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.createdTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.updatedTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.remarks }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            round
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 用于增加和修改的模态框 -->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
      <el-form :model="formData">
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="formData.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px">
          <el-input v-model="formData.password" autocomplete="off"></el-input>
        </el-form-item>
         <el-form-item label="确认密码" label-width="120px" >
          <el-input v-model="formData.passwordOk" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="120px">
          <el-input v-model="formData.remarks" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>

    <!-- //分页条 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.currentPage"
        :page-size="pager.pageSize"
        :page-sizes="[5, 7, 10, 15, 20]"
        layout="sizes,prev, pager,next,total, jumper"
        :total="pager.totalSize"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getUsersList,
  addUser,
  updateUser,
  deleteUserById,
  getUserByQuery,
} from "../../../APi/users";

export default {
  data() {
    return {
      /// 模糊查询的参数对象
      formInline:{
        //文本框里的实参
        "queryDatas":"",
      },
      tableData: [],

      //定义一个更新时获取到的index用于修改是使用
      currentIndexByUpdate: 0,

      //分页
      pager: {
        // 当前页，默认开启去第一页
        currentPage: 1,

        //每页显示多少条数据
        pageSize: 5,

        //总共有几条数据
        totalSize: 0,
      },
      formData: {
        currentId: 0,
        username: "",
        password: "",
        passwordOk: "",
        remarks: "",
      },

      dialogFormVisible: false

    };
  },

  methods: {
      //禁止输入空格
      keydown(e)
      {
         if (e.keyCode==32) {
            e.returnValue=false
         }    
      },

    //点击查询按钮时
    onSubmit() {
        
        console.log("查询");    
        if (this.formInline.queryDatas=="") {

          console.log("为空刷新界面");
          //重新刷新页面，并将this.pager重新插入
            this.fetchData(this.pager);
        }else{
        getUserByQuery(this.formInline)
        .then(({data}) => {

            console.log(this.formInline);

          var res=data.data

          this.tableData=res
          this.pager.totalSize=this.tableData.length
          console.log(res);

          // res.data.data
        })
        .catch((err) => {
          console.log(err);
        });
        }
  
    },

    //点击新增按钮时
    handleAdd() {   

      //进来时清空模态框里的所有文本内容
     (this.formData.passwordOk = ""), (this.formData.password = ""), (this.formData.username = ""), (this.formData.remarks = "");

      this.dialogFormVisible = true;
    },
    //当前点击编辑时
    handleEdit(index, row) {
      // console.log(index, row);
      this.currentIndexByUpdate = index;

      //将当前获取到的编辑的信息赋给formData
      this.formData.currentId = row.id;
      this.formData.username = row.username;
      this.formData.remarks = row.remarks;

      this.dialogFormVisible = true;
    },

    //当前点击删除时
    handleDelete(index, row) {
      // console.log(index);
      // console.log(row);

      this.$confirm("确定要删除当前用户吗？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let id = row.id;
          console.log("确认删除");
          //执行删除的函数，要传id
          deleteUserById(id)
            .then(() => {
              //动态去除删除的行
              this.tableData.splice(index, 1);

              this.pager.totalSize -= 1;

              console.log("当前总数：" + this.pager.totalSize);

              //调用fetchData,从新刷新页面
              this.fetchData(this.pager);

              // 判断当前页*每页数量是否=总数量
              if (this.pager.totalSize % this.pager.pageSize < 1) {
                var page = this.pager.currentPage - 1;
                console.log(page);
                this.handlePageIndexChange(page);
              } else {
                console.log(this.pager.totalSize % this.pager.pageSize);
              }
            })
            .catch((err) => {
              console.log(err);
            });

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //模态框确定键
    handleSave() {          
          //判断两次输入的密码是否一致
        if (this.formData.password!==this.formData.passwordOk) {
              this.$alert("两次输入的密码不一致", "添加", {
                confirmButtonText: "确定",
              });
              return;
        }

      this.dialogFormVisible = false;
    
      // 判断有没有this.formData.id是否为0,0则代表添加
      if (this.formData.currentId == 0) {

          console.log("新增");
        //执行添加的方法
        addUser(this.formData)
          .then(({ data }) => {
             
            var res = data;
            
            console.log(res);
            //当用户名为undefined
            if (res.username !== undefined) {
              this.tableData.push(res);

              var page =
                parseInt(this.pager.totalSize / this.pager.pageSize) + 1;
              this.handlePageIndexChange(page);
            } else {
              this.$alert("用户名不可为空,添加失败了", "添加", {
                confirmButtonText: "确定",
              });
            }           
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
         console.log("修改");
        var id = this.formData.currentId;
        //执行更新的方法
        updateUser(id, this.formData)
          .then(({ data }) => {
            var res = data;

            //当用户名为undefined
            if (res.username !== undefined) {
              this.tableData.splice(this.currentIndexByUpdate, 1, res);
            } else {
              this.$alert("用户名不可为空,修改失败了", "修改", {
                confirmButtonText: "确定",
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    //模态框取消键
    handleCancel() {
      this.dialogFormVisible = false;
      console.log(this.formData);
    },
    //当选择每页多少条数据时
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pager.pageSize = val;
      //重新刷新页面，并将this.pager重新插入
      this.fetchData(this.pager);
    },

    // 当改变页码后，重新拉取数据
    handlePageIndexChange(val) {    
      this.pager.currentPage = val;
       console.log("当前页：" + this.pager.currentPage);
      //重新刷新页面，并将this.pager重新插入
      this.fetchData(this.pager);
    },

    //定义一个方法，用于获取数据
    fetchData(pager) {
      getUsersList(pager)
        .then(({ data }) => {
          var res = data;
          // console.log(res);
          //将分页后的数据传给tableData
          this.tableData = res.data;
          this.pager = res.pager;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },

  //生命周期函数
  mounted() {
    this.fetchData(this.pager);

    // getById(1)
    //   .then(({ data }) => {
    //     console.log(data);
    //   })
    //   .catch((err) => {
    //     console.log(err);
    //   });
  },
};
</script>
<style>
.el-table td,
.el-table th.is-leaf {
  text-align: center;
}
.el-table {
  margin-top: 20px;
  color: black;
  background-color: chartreuse;
}
.el-pagination {
  color: cornflowerblue;
  font-size: 20px;
}
/* 分页栏 */
.el-pagination button,
.el-pagination span:not([class*="suffix"]) {
  color: aliceblue;
  font-size: 20px;
}
.el-card {
  background: none;
}
/*整个用户表的样式*/
#userTable {
  height: 500px;
  margin-top: 20px;
}
</style>
